class Solution {
public:
    int ans = 0;

    int longestUnivaluePath(TreeNode* root) {
        dfs(root);
        return ans;
    }

private:
    
    int dfs(TreeNode* node) {
        if (!node) return 0;

        int left = dfs(node->left);
        int right = dfs(node->right);

        int leftPath = (node->left && node->left->val == node->val) ? left + 1 : 0;
        int rightPath = (node->right && node->right->val == node->val) ? right + 1 : 0;

       
        ans = std::max(ans, leftPath + rightPath);

       
        return std::max(leftPath, rightPath);
    }
};

